<?php
namespace Home\Controller;
use Home\Controller\BaseController;
use Think\Page;
class IndexController extends BaseController {
	public function __construct(){
		parent::__construct();
		$this->topicMod = D('ArticleClass');
		$this->questionMod = D('Article');
		$this->commentMod = D('Comment');
		$this->followMod = D('Follow');
	}
	/**
	 * 话题列表
	 */
    public function index(){
    	$where = array();
    	$order = 'ac_sort';
    	$count = $this->topicMod->where($where)->count();
    	$page = new Page($count,4);
    	$list = $this->topicMod->where($where)->limit($page->firstRow.','.$page->listRows)->order($order)->select();
    	$this->assign('list',$list);
    	$this->assign('page',$page->show());
    	$this->display();
    }
    /**
     * 论题列表
     */
    public function listing(){
    	$where = array();
    	$search = trimall($_GET['key']);
    	if (!empty($search)) {
    		$map['article_title'] = array('LIKE','%'.$search.'%');
	    	$map['article_key'] = array('LIKE','%'.$search.'%');
	    	$map['article_desc'] = array('LIKE','%'.$search.'%');
	    	$map['_logic'] = 'or';
	    	$where['_complex'] = $map;
    	}
    	if (intval($_GET['topic'])) {
    		$topic = intval($_GET['topic']);
    		$where['ac_id'] = $topic;
    		$ac = $this->topicMod->where(array('ac_id'=>$topic))->find();
    		if (!empty($ac)) {
    			if (!empty($ac['ac_title'])) {
    				$param['title'] = $ac['ac_title'];
    			}
    			if (!empty($ac['ac_key'])) {
    				$param['keywords'] = $ac['ac_key'];
    			}
    			if (!empty($ac['ac_desc'])) {
    				$param['description'] = $ac['ac_desc'];
    			}
    			if (!empty($param)) {
    				$this->assign('seo',seo($param));
    				unset($param);
    			}
    		}
    	}
    	$order = 'article_time desc';
    	$count = $this->questionMod->where($where)->count();
    	$page = new Page($count,20);
    	$list = $this->questionMod->where($where)->limit($page->firstRow.','.$page->listRows)->order($order)->select();
    	$this->assign('list',$list);
    	$this->assign('page',$page->show());
    	$this->display();
    }
    /**
     * 论题详情
     */
    public function question(){
   	
    	$id = intval($_GET['id']);
    	$where['article_id'] = $id;
    	$where['article_show'] = 1;
    	$info = $this->questionMod->where($where)->find();
    	unset($where);
    	if (empty($info)) {
    		$this->error('没有找到该论题');
    	}else {
    		$where['article_id'] = $id;
    		$where['pid'] = 0;
    		$order = 'addtime desc';
    		$count = $this->commentMod->where($where)->count();
    		$page = new Page($count,5);
    		$list = $this->commentMod->where($where)->limit($page->firstRow.','.$page->listRows)->order($order)->select();

    		foreach ($list as $key => $val){
    			$where['article_id'] = $id;
    			$where['pid'] =  array('gt',0);
    			$where['c_pid'] = array('eq',$val['id']);
    			$where['position'] = array('eq',1);
    			$limit = 2;
                //赞成列表
    			$list[$key]['agree_list'] = $this->commentMod->relation(true)->where($where)->limit($limit)->order($order)->select();
    			foreach ($list[$key]['agree_list'] as $k => $v){
    				$notcan = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$v['id'],'follow_type'=>array('IN','Agree,Against')))->count();
    				if ($notcan == 0) {
    					$list[$key]['agree_list'][$k]['agree'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$v['id'],'follow_type'=>'Agree'))->count();
    					$list[$key]['agree_list'][$k]['against'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$v['id'],'follow_type'=>'Against'))->count();
    				}
    			}
    			$count = $this->commentMod->relation(true)->where($where)->count();
    			if ($count > $limit) {
    				$list[$key]['agree_next'] = 1;
    			}
                //反对列表
    			$where['position'] = array('eq',-1);
    			$list[$key]['against_list'] = $this->commentMod->relation(true)->where($where)->limit($limit)->order($order)->select();
    			foreach ($list[$key]['against_list'] as $k => $v){
    				$notcan = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$v['id'],'follow_type'=>array('IN','Agree,Against')))->count();
    				if ($notcan == 0) {
    					$list[$key]['against_list'][$k]['agree'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$v['id'],'follow_type'=>'Agree'))->count();
    					$list[$key]['against_list'][$k]['against'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$v['id'],'follow_type'=>'Against'))->count();
    				}
    			}
    			$count = $this->commentMod->relation(true)->where($where)->count();
    			if ($count > $limit) {
    				$list[$key]['against_next'] = 1;
    			}
                //获取自己对论点评论的赞和反对数
    			$notcan = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$val['id'],'follow_type'=>array('IN','Agree,Against')))->count();
    			if ($notcan == 0) {
    				$list[$key]['agree'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$val['id'],'follow_type'=>'Agree'))->count();
    				$list[$key]['against'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$val['id'],'follow_type'=>'Against'))->count();
    			}
                //获取自己对论点评论的值和不值数
                $notcan = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$val['id'],'follow_type'=>array('IN','Useful,Useless')))->count();
                if ($notcan == 0) {
                    $list[$key]['useful'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$val['id'],'follow_type'=>'Useful'))->count();
                    $list[$key]['useless'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$val['id'],'follow_type'=>'Useless'))->count();
                }

    			$list[$key]['follow'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$val['id'],'follow_type'=>'Comment'))->count();
    		}
            //seo
    		if (!empty($info['article_title'])) {
    			$seo_param['title'] = $info['article_title'];
    		}
    		if (!empty($info['article_key'])) {
    			$seo_param['keywords'] = $info['article_key'];
    		}
    		if (!empty($info['article_desc'])) {
    			$seo_param['description'] = $info['article_desc'];
    		}
            //擅长领域
    		$Exper = M('Expertise')->where(array('ac_id'=>$info['ac_id']))->select();
    		if (is_array($Exper)) {
    			$Expertise = array();
    			foreach ($Exper as $key => $val){
    				$Expertise[] = M('Member')->where(array('member_id'=>$val['member_id']))->find();
    			}
    			$this->assign('member_list',$Expertise);
    		}
            //不明白这个更新优什么用
			$this->commentMod->where(array('article_id'=>$id,'member_id'=>$this->mid))->setField('new_comment',0);

//print_r($list);exit;
    		$this->assign('seo',seo($seo_param));
    		$this->assign('info',$info);
    		$this->assign('list',$list);
    		$this->assign('page',$page->show());
    		$this->session_id = session('member_id'); 
    		
    		//后面加的可注释
    		$count_comm = $this->commentMod->field(member_id)->distinct(true)->select();
    		foreach($count_comm as $key=>$value){
    			$ucount=$this->commentMod->where('member_id="'.$value['member_id'].'"')->count();
    			/* $list_comm[$key]['username']=$this->commentMod->order($ucount)->getField('member_id'); */
    		}
//    		P($ucount);
    		
    		
    		$grop['member_id'] = array('NEQ',$this->mid);
    		$this->grop = M('member')->order('vip_level desc')->where($grop)->limit(3)->select();
    		
    		$this->display();
    	}
    }
    
    //加载更多
    public function more_num()
    {

//    	$info = $this->questionMod->where($where)->find();
        $info['article_id']=$_GET['aid'];
    	$num = intval($_GET['num'])  ;
    	$v =  M('member')->order('vip_level desc')->limit($num+1,3)->select();

    	$moreinfo = '';
    	if(is_array($v) && !empty($v))
    	{
    		foreach($v as $vo)
    		{    
    			if($vo['member_id'] == $this->mid){
    				unset($vo['member_id']);
    				exit;
    			}else{
    				if(!empty($vo[avatar])){
    					$img = C('SiteUrl').'/Uploads/'.$vo['avatar'];
    				}else{
    					$img = C('SiteUrl').'/Public/home/img/defaultpic.png';
    				}
    				$moreinfo.='<li class="list_num">
								<a class="member-pic" href="">
								<img src='.$img.' width="50" height="50" alt="">
								</a>
								<button class="Invited-but" onclick="invitation('.$info['article_id'].','.$vo['member_id'].')">邀请辩论</button>
								 <div class="member-info">
								 	  <a class="member-name" href="">'.$vo['member_name'].'</a> <span> '.$vo['introduce'].'</span>
								 	  <div class="profession">'.$vo['profession'].'</div>
								 </div>
								 <div class="clear"></div>
							</li>';    					
    			}
    		}
    	}
    	echo $moreinfo;
    }    
    
    
    /**
     * ajax发表评论
     */
    public function comment(){
    	if (IS_AJAX) {
    		if ($this->mid) {
    			$data['article_id'] = intval($_POST['id']);
	    		$data['member_id'] = $this->mid;
	    		$data['addtime'] = NOW_TIME;
	    		$data['pid'] = intval($_POST['pid']);
	    		$data['content'] = str_rp($_POST['content']);
	    		$data['position'] = intval($_POST['position']);
	    		$data['c_pid'] = intval($_POST['c_pid']);
	    		$data['reply_member_id'] = $this->commentMod->where(array('id'=>$data['pid']))->getField('member_id');
                $path=RUNTIME_PATH.'Exts/keyword.php';
                $keyword_data= include($path);
                //屏蔽污秽词语
                foreach($keyword_data as $key=>$value){
                    $content_length=mb_strlen($value,'UTF8');
                    $replace_str="";
                    for($i=0;$i<$content_length;$i++){
                        $replace_str.="*";
                    }
                    $data['content']=preg_replace('/'.$value.'/',$replace_str,$data['content'],-1);
                }

	    		$res = $this->commentMod->add($data);
	    		if ($res) {
	    			$rs = $this->commentMod->where(array('id'=>$data['pid']))->setInc('new_comment');
                    $res=array('status'=>true,'msg'=>'发表观点成功.'.$rs);
	    		}else {
                    $res=array('status'=>false,'msg'=>'发表观点失败.');
	    		}
    		}else {
    			$res = array('status'=>false,'msg'=>'请登录后再发表观点.');
    		}
    		echo json_encode($res);
    	}
    }
    /**
     * ajax加载更多二级评论
     */
    public function getMoreComment(){
    	if (IS_AJAX) {
    		$limit = 10;
    		$order = 'addtime desc';
    		$id = intval($_POST['id']);
    		$position = intval($_POST['position']);
    		$start = intval($_POST['start']);
    		$aid = intval($_POST['aid']);
    		$where['c_pid'] = $id;
    		$where['position'] = $position;
    		$list = $this->commentMod->relation(true)->where($where)->limit($start,$start+$limit)->order($order)->select();
    		foreach ($list as $key => $val){
    			$list[$key]['agree'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$val['id'],'follow_type'=>'Agree'))->count();
    			$list[$key]['against'] = $this->followMod->where(array('member_id'=>$this->mid,'follow_id'=>$val['id'],'follow_type'=>'Against'))->count();
    		}
    		$info = '';
    		foreach ($list as $key => $v){
    			$info .= '<div class="member-box">
								<div class="com-name">
								<a class="memberID" href="">'.get_member_nickname($v['Member']['member_id']).':</a>';
    			if ($v['pid'] != $v['c_pid']){
    				if (get_reply_position($v['id'])) {
    					$reply_position = "同意";
    				}else{
    					$reply_position = "反驳";
    				}
    				$info .= '<span class="rep"> '.$reply_position.' </span><a href="">'.get_member_nickname($v['reply_member_id']).'</a>';
    			}
    			$info .= '</div>
							<div class="com-container">'.$v['content'].'</div>
							<div class="pendant">
								<span class="switch">
								<a class="suppor-reply" aid="'.$aid.'" bid="'.$v['id'].'" cid="childcomment" did="'.$position.'" eid="'.$id.'" href="javascript:">·支持回复</a>
								<a class="suppor-fanbo" aid="'.$aid.'" bid="'.$v['id'].'" cid="childcomment" did="'.$position*(-1).'" eid="'.$id.'" href="javascript:">·反驳</a></span>';
				$info .= '<a id="follow_'.$v['id'].'_1" ';
    			if ($v['agree'] == 0) {
    				$info .= 'class="edge unbind" href="javascript:follow('.$v['id'].',1)"';
    			}else {
    				$info .= 'class="edge" href="javascript:" style="color: rgb(195, 188, 188); cursor: text;"';
    			}
				$info .= '>·赞成(<i>'.$v['agree_num'].'</i>)</a>';
				$info .= '<a id="follow_'.$v['id'].'_-1" ';
				if ($v['against'] == 0) {
					$info .= 'class="edge unbind" href="javascript:follow('.$v['id'].',-1)"';
				}else {
					$info .= 'class="edge" href="javascript:" style="color: rgb(195, 188, 188); cursor: text;"';
				}
		 	 	$info .= '>·反对(<i>'.$v['against_num'].'</i>)</a>';
		 	 	$info .= '</div><div class="txtbox"></div></div>';
    		}
    		if (!empty($info)) {
    			$end = $start+count($list);
    			$nextstatus = $this->commentMod->relation(true)->where($where)->limit($end,$end+1)->select();
    			$nextstatus = count($nextstatus);
    			$res = array('status'=>true,'list'=>$info,'count'=>$end,'nextstatus'=>$nextstatus);
    		}else {
    			$res = array('status'=>false,'list'=>$info);

    		}
    		echo json_encode($res);
    	}
    }
    /**
     * ajax收藏赞成反对
     */
    public function follow(){
    	if (IS_AJAX) {
    		$data['follow_id'] = intval($_POST['id']);
    		$data['member_id'] = $this->mid;
    		$position = intval($_POST['position']);
    		if ($position == 1) {
    			$data['follow_type'] = 'Agree';
    		}elseif ($position == -1){
    			$data['follow_type'] = 'Against';
    		}elseif ($position == 0){
    			$data['follow_type'] = 'Comment';
    		}
    		$res = $this->followMod->where($data)->count();
    		if ($res==0) {
                //只是执行了这个逻辑，else更本没用
    			$data['follow_time'] = NOW_TIME;
    			$rs = $this->followMod->add($data);
    			if ($rs) {
	    			if ($position == 1) {
		    			$this->commentMod->where(array('id'=>$data['follow_id']))->setInc('agree_num');
		    		}elseif ($position == -1){
		    			$this->commentMod->where(array('id'=>$data['follow_id']))->setInc('against_num');
		    		}
    			}
    		}else {
    			$rs = $this->followMod->where($data)->delete();
    			if ($rs) {
    				if ($position == 1) {
    					$this->commentMod->where(array('id'=>$data['follow_id']))->setDec('agree_num');
    				}elseif ($position == -1){
    					$this->commentMod->where(array('id'=>$data['follow_id']))->setDec('against_num');
    				}
    			}
    		}
    	}
    }

    /**
     * ajax值与不值
     */
    public function useful(){
        if (IS_AJAX) {
            $data['follow_id'] = intval($_POST['id']);
            $data['member_id'] = $this->mid;
            $position = intval($_POST['position']);
            if ($position == 1) {
                $data['follow_type'] = 'Useful';
            }elseif ($position == -1){
                $data['follow_type'] = 'Useless';
            }elseif ($position == 0){
                $data['follow_type'] = 'Comment';
            }
            $res = $this->followMod->where($data)->count();
            if ($res==0) {
                $data['follow_time'] = NOW_TIME;
                $rs = $this->followMod->add($data);
                if ($rs) {
                    if ($position == 1) {
                        $this->commentMod->where(array('id'=>$data['follow_id']))->setInc('useful_num');
                    }elseif ($position == -1){
                        $this->commentMod->where(array('id'=>$data['follow_id']))->setInc('useless_num');
                    }
                }
            }else {
                $rs = $this->followMod->where($data)->delete();
                if ($rs) {
                    if ($position == 1) {
                        $this->commentMod->where(array('id'=>$data['follow_id']))->setDec('useful_num');
                    }elseif ($position == -1){
                        $this->commentMod->where(array('id'=>$data['follow_id']))->setDec('useless_num');
                    }
                }
            }
        }
    }
    /**
     * ajax邀请
     */
    public function invitation(){
    	if (IS_AJAX) {
    		$data['member_id'] = intval($_POST['mid']);
    		$data['follow_id'] = intval($_POST['aid']);
    		$data['follow_type'] = 'Invitation';
    		$res = $this->followMod->where($data)->count();
    		if ($res == 0) {
    			$data['follow_time'] = NOW_TIME;
    			$rs = $this->followMod->add($data);
    		}
    	}
    }

    //打赏
    public function dashang(){
        if (IS_POST) {
            $where['id'] = intval($_POST['id']);
            $count = intval($_POST['count']);
            $info = $this->commentMod->where($where)->find();
            $editer_id=0;
            if($info['pid']!=0){
                $editer_id=$info['reply_member_id'];
            }else{
                $editer_id=$info['member_id'];
            }
            //打赏
            $editer_id=$info['reply_member_id'];
            $yushu=$count%2;
            $half=$count/2;
            $half_more=$half+$yushu;

            //网站收入



            //编辑者收入




//            $res = $this->commentMod->where($where)->save($data);
//            if ($res) {
                $this->success('打赏成功');
//            }else {
//                $this->error('打赏失败');
//            }
        }elseif (IS_GET) {
            $id = intval($_GET['id']);
            $this->assign('id',$id);
            $this->display();
        }
    }

    //举报
    public function report(){
        if (IS_POST) {
            $this->check_login();
            $where['id'] = intval($_POST['id']);
            $where['member_id'] = $this->mid;
            $exist=$this->commentMod->where($where)->find();
            if(!empty($exist)){
                showMessage('不能举报自己哟','','html','error');
            }
            $where['member_id'] =array('neq',$this->mid);
            $info = $this->commentMod->where($where)->find();
            $report_list=count(unserialize($info['report_records'])) ? unserialize($info['report_records']) : array();

            if(exist_key_vaule_array1d_in_array2d($report_list,0,$this->mid)){
                showMessage('你已经举报过了，请不要重复举报','','html','error');
            }
            $report_list[]=array(
                'member_id'=>$this->mid,
                'content'=>str_rp(trim($_POST['content'])),
                'status'=>0,
                'add_time'=>NOW_TIME,
            );
            $data['report_records'] = serialize($report_list);
            $res = $this->commentMod->where($where)->save($data);
            if ($res) {
                $this->success('举报成功');
            }else {
                $this->error('举报失败');
            }
        }elseif (IS_GET) {
            $this->display();
        }
    }


    //重新编辑
    public function rewrite(){
    	if (IS_POST) {
    		$where['id'] = intval($_POST['id']);
    		$where['member_id'] = $this->mid;
    		$data['addtime'] = NOW_TIME;
    		$data['content'] = str_rp(trim($_POST['content']));
            $path=RUNTIME_PATH.'Exts/keyword.php';
            $keyword_data= include($path);
            //屏蔽污秽词语
            foreach($keyword_data as $key=>$value){
                $content_length=mb_strlen($value,'UTF8');
                $replace_str="";
                for($i=0;$i<$content_length;$i++){
                    $replace_str.="*";
                }
                $data['content']=preg_replace('/'.$value.'/',$replace_str,$data['content'],-1);
            }
    		$res = $this->commentMod->where($where)->save($data);
    		if ($res) {
    			$this->success('编辑成功');
    		}else {
    			$this->error('编辑失败');
    		}
    	}elseif (IS_GET) {
    		$where['id'] = intval($_GET['id']);
    		$where['member_id'] = $this->mid;
    		$info = $this->commentMod->where($where)->find();
    		$this->assign('info',$info);
    		$this->display();
    	}
    }

    //
    /**
     * ajax订阅
     */
    public function dingyue(){
        if (IS_AJAX) {
            $data['comment_id'] = intval($_POST['id']);
            $data['ac_id'] = intval($_POST['ac_id']);
            $data['member_id'] = $this->mid;
            $res = M('article_dy')->where($data)->count();
            $json_data = array();
            $cost_coin=0;
            if ($res==0) {
                $member_info = M('member')->where(array('member_id'=>$this->mid))->find();
                $where['article_id'] = intval($_POST['ac_id']);
                $where['id'] = intval($_POST['id']);
                $where['pid'] = 0;
                $comment_info = $this->commentMod->where($where)->find();
                $content_length=mb_strlen($comment_info['content'],'UTF8');
                //论点订阅加收金币计算（看论点）
                if($content_length>50){
                    //多支付金币
                    for($i=50;$i<$content_length;$i+10){
                        $cost_coin+=1;  //每10个字加收一金币，不足10字也加收一金币
                        if($cost_coin==10){
                            //到了10金币后就不加收金币了
                            break;
                        }
                    }
                }
                //评论回复订阅加收金币（看评论回复：论点回复数量每超过1个，查看时需要再多支付1个金币，最多支付10个）




                //值加收金币（论点值：只有收费论题才有值或不值，只有订阅了以后的的用户才能操作，点击数超过1000个，查看时需要再多支付1个金币，最多支付10个）




                //开始插入订阅记录，用户扣金币（只有付费论题才需要订阅和打包，否则不显示操作该操作按钮）
                if($member_info['coin'] > 0 && $member_info['coin']>=$cost_coin){
                    $data['add_time'] = NOW_TIME;
                    $rs = M('article_dy')->add($data);
                    if($rs){
                        /*插入金币和预存款动态记录表（5张表记录操作，需要写一个公用方法）
                        operate

                        */

                        $json_data=array('status'=>true,'msg'=>'订阅成功！');
                    }else{
                        $json_data=array('status'=>true,'msg'=>'订阅失败！');
                    }
                }else{
                    $json_data=array('status'=>true,'msg'=>'您的金币数不够哦！');
                }
            }else {
                $json_data=array('status'=>true,'msg'=>'已订阅，不需重复订阅！');
            }
            echo json_encode($json_data);exit;
        }
    }
}